package com.bby.screentool.event;

import android.util.Log;

import com.bby.screentool.exception.ServiceException;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.ObjectUtil;

public class ActionEventHandler {

    private List<Field> EVENTS;
    private Map<String, Method> eventMap = new HashMap<>();
    private ActionEventListener listener;

    private ActionEventHandler() {
    }

    public static ActionEventHandler build(ActionEventListener listener) {
        ActionEventHandler handler = new ActionEventHandler();
        handler.listener = listener;
        for (Method method : listener.getClass().getMethods()) {
            ActionEvent anno = method.getAnnotation(ActionEvent.class);
            if (ObjectUtil.isEmpty(anno)) {
                continue;
            }
            handler.eventMap.put(anno.value(), method);
        }
        return handler;
    }

    public void invoke(Action action) throws ServiceException {
        Method method = eventMap.get(action.getAction());
        if (method==null){
            Log.e("ActionEventHandler","参数错误");
            return;
        }
        if (ObjectUtil.isEmpty(method.getParameterTypes())) {
            throw new ServiceException("ActionEvent Method Parameter Error: "+method);
        }
        try {
            method.invoke(listener, action);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new ServiceException("分发事件失败",e);
        }
    }
}
